/**
 * 工具类命名空间
 *
 * @type {{}}
 */
var Util = window.Util || {};

/**
 * 资源选择器
 */
Util.select = new function () {
    var select = this;

    var defaultEntityId = '81212';// 资源模版配置ID，默认是PC服务器
    var defaultTitle = '资源选择器';// 资源选择器默认标题，默认资源选择器
    var defaultGridUrl = '/resourceEntity/queryPageList';// 默认资源选择器查询URL
    var defaultGridPostData = {};// 默认资源选择器查询条件
    var resourceSelectModal = 'resourceSelectModal';
    var $resourceSelectModal = $('#resourceSelectModal');
    var $querySelectPanel = $querySelectPanel;
    var $querySelectFields = $('#querySelectFields');
    var grid_selecter_select;
    var $grid_selecter_select;
    var pager_selecter_select;
    var parent_column_select;

    /**
     * 初始化资源选择器
     *
     * @param entityId
     * @param title
     * @param okSelectCallback 返回false，可阻止关闭窗口
     * @param gridUrl
     * @param gridPostData
     */
    select.init = function (entityId, title, okSelectCallback, gridUrl, gridPostData) {
        if (entityId) {
            defaultEntityId = entityId;
        }
        if (title) {
            defaultTitle = title;
        }
        if (gridUrl) {
            defaultGridUrl = gridUrl;
        }
        if (gridPostData) {
            defaultGridPostData = gridPostData;
        }
        if (typeof okSelectCallback === 'function') {
            default_ok_select_callback = okSelectCallback;
        }
        $('#selectTitle').html(defaultTitle);
        $.ajax({
            type: 'post',
            async: true,// 异步请求
            url: ctx + '/resourceConf/queryResourceSelectConf?random=' + Math.random(),
            dataType: 'json',
            data: {
                entityId: defaultEntityId
            },
            success: function (data) {
                var resourceSelectConf = data.result;
                initSearch(resourceSelectConf.searchEles);
                initGrid(resourceSelectConf.jqGrid);
            }
        });


    };

    /**
     * 打开资源选择器模态框
     */
    select.open = function () {
        if ($('#searSelectBtn').attr('aria-expanded') == 'true') {
            $('#searSelectBtn').trigger('click');
        }
        $.launchDialog(resourceSelectModal);
    };

    /**
     * 关闭资源选择器模态框
     *
     * @param callback
     */
    select.close = function (callback) {
        if (typeof callback === "function") {
            callback();
        }
        $resourceSelectModal.modal('hide');
    };

    /**
     * 获取选择的记录
     *
     * @returns {any[]}
     */
    select.getSelectRows = function () {
        var rowDatas = new Array();
        var rowIds = $grid_selecter_select.jqGrid('getGridParam', 'selarrrow');
        $.each(rowIds, function (idx, rowId) {
            rowDatas.push($grid_selecter_select.jqGrid('getRowData', rowId));
        });
        return rowDatas;
    };


    ok_select = function () {
        if (typeof default_ok_select_callback === "function") {
            var result = default_ok_select_callback();
            if (result != false) {
                select.close();
            }
        }
    };

    default_ok_select_callback = function () {
        select.close();
    };

    initSearch = function (searchEles) {
        // 生成模糊查询
        var searchHtml = '';
        var searchHtml1 = '';
        $.each(searchEles, function (index, ele) {
            if (ele.eleType == 'select') {
                searchHtml1 += '<div class="form-group col-lg-6 col-md-12">';
                searchHtml1 += '<label class="col-sm-4 control-label no-padding-right">' + ele.title + '</label>';
                searchHtml1 += '<div class="col-sm-8">';
            } else {
                searchHtml += '<div class="form-group col-lg-6 col-md-12">';
                searchHtml += '<label class="col-sm-4 control-label no-padding-right">' + ele.title + '</label>';
                searchHtml += '<div class="col-sm-8">';
            }
            switch (ele.eleType) {
                case 'input':
                    switch (ele.inputType) {
                        case 'text':
                            searchHtml += '<input type="text" name="' + ele.name + '" class="form-control"/>';
                            break;
                        case 'radio':
                            searchHtml += '<div class="radio">';
                            $.each(ele.items, function (index, item) {
                                searchHtml += '<label>\
                                                <input class="ace" name="' + ele.name + '" type="radio" value="' + item.value + '">\
                                                <span class="lbl"> ' + item.name + '</span>\
                                             </label>';
                            });
                            searchHtml += '</div>';
                            break;
                        case 'checkbox':
                            searchHtml += '<div class="checkbox">';
                            $.each(ele.items, function (index, item) {
                                searchHtml += '<label>\
                                                <input class="ace" name="' + ele.name + '" type="checkbox" value="' + item.value + '">\
                                                <span class="lbl"> ' + item.name + '</span>\
                                            </label>';
                            });
                            searchHtml += '</div>';
                            break;
                        default:
                            break;
                    }
                    break;
                case 'select':
                    searchHtml1 += '<select class="chosen-select form-control" name="' + ele.name + '" data-no_results_text="未匹配到">';
                    searchHtml1 += '    <option value=""> 请选择 </option>';
                    $.each(ele.items, function (index, item) {
                        searchHtml1 += '    <option value="' + item.value + '"> ' + item.name + ' </option>';
                    });
                    searchHtml1 += '</select>';
                    break;
                case 'textarea':
                    searchHtml += '<textarea class="form-control limited" name="' + ele.name + '" maxlength="' + ele.eleLength + '"></textarea>';
                    break;
                case 'date':
                    searchHtml += '<div class="input-group">\
                                    <input class="form-control date-picker" name="' + ele.name + '" type="text"/>\
                                    <span class="input-group-addon">\
                                        <i class="fa fa-calendar bigger-110"></i>\
                                    </span>\
                                </div>';
                    break;
                case 'datetime':
                    searchHtml += '<div class="input-group">\
                                    <input class="form-control date-timepicker" name="' + ele.name + '" type="text"/>\
                                    <span class="input-group-addon">\
                                        <i class="fa fa-clock-o bigger-110"></i>\
                                    </span>\
                                </div>';
                    break;
                default:
                    break;
            }
            searchHtml += '</div></div>';
            searchHtml1 += '</div></div>';
        });
        searchHtml += searchHtml1 + '<div class="form-group col-lg-6 col-md-12">\
                            <div class="pull-right" style="margin-right: 12px;">\
                                <button id="searchSelectBtn" class="btn btn-sm btn-info">\
                                    <i class="ace-icon glyphicon glyphicon-search align-center bigger-110"></i>\
                                    查询\
                                </button>\
                                    <button id="resetSelectBtn" class="btn btn-sm btn-info">\
                                    <i class="ace-icon glyphicon glyphicon-repeat align-center bigger-110"></i>\
                                    重置\
                                </button>\
                            </div>\
                       </div>';
        $querySelectFields.html(searchHtml);

        $querySelectPanel = $('#querySelectPanel'); //重新初始化

        // 显示隐藏查询条件
        $('#searSelectBtn').click(function () {
            $(this).find('i').toggleClass('fa-arrow-down');
            $(this).find('i').toggleClass('fa-arrow-up');
        });

        $querySelectPanel.on('shown.bs.collapse', function () {
            initPlugins();
            rseizeSelect_select();
        });

        $('#searchSelectBtn').click(function () {
            reloadJqGrid_select();
        });

        $('#ok_select').click(function () {
            ok_select();
        });

        // 重置查询表单
        $('#resetSelectBtn').click(function () {
            $querySelectPanel.find(':input(:text)').each(function () {
                $(this).val('');
            });
            $querySelectPanel.find('input[type=checkbox],input[type=radio]').each(function () {
                $(this).removeAttr('checked');
            });
            reloadJqGrid_select();
        });

        $(document).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
            if ($grid_selecter_select) {
                $grid_selecter_select.jqGrid('setGridWidth', parent_column_select.width());
            }
        });
    };

    initGrid = function (jqGrid) {
        // 重置jqgrid
        $.jgrid.gridUnload('grid-table-select');

        grid_selecter_select = '#grid-table-select';
        $grid_selecter_select = $(grid_selecter_select);
        pager_selecter_select = '#grid-pager-select';
        parent_column_select = $grid_selecter_select.closest('[class*="col-"]');

        var colNames = jqGrid.colNames;
        var colModels = jqGrid.colModels;
        $grid_selecter_select.jqGrid({
            url: ctx + defaultGridUrl + '?random=' + Math.random(),
            mtype: 'post',
            datatype: 'json',
            height: '100%',
            colNames: colNames,
            colModel: colModels,
            autowidth: true,
            shrinkToFit: false,
            autoScroll: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: rowNum,
            rowList: rowList,
            pager: pager_selecter_select,
            sortname: jqGrid.sortname,
            sortorder: jqGrid.sortorder,
            jsonReader: jsonReader,
            beforeRequest: grid_post_data,
            loadComplete: function () {
                setTimeout(function () {
                    $grid_selecter_select.jqGrid('setGridWidth', parent_column_select.width());
                }, 20);
            }
        });

        //navButtons
        $grid_selecter_select.jqGrid('navGrid', pager_selecter_select, {
            add: false, edit: false, del: false, search: false, view: false, refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green'
        });
    };

    grid_post_data = function () {
        defaultGridPostData.entityId = defaultEntityId;
        $querySelectPanel.find('[name^="search."]').each(function () {
            var $this = $(this);
            defaultGridPostData[$this.attr('name')] = $this.val();
        });
        $.extend($grid_selecter_select.getGridParam('postData'), defaultGridPostData);
    };

    reloadJqGrid_select = function () {
        $grid_selecter_select.trigger('reloadGrid', [{page: 1}]);
    };

    rseizeSelect_select = function () {
        setTimeout(function () {
            $querySelectPanel.find('.chosen-select').each(function () {
                var $this = $(this);
                $this.parent().find('.chosen-container').css({'width': $this.parent().width()});
            });
        }, 1);
    };

    initPlugins = function () {

        if ($querySelectPanel.find('.chosen-select')) {
            $querySelectPanel.find('.chosen-select').chosen();
        }

        //textarea.limited plugin init
        if ($querySelectPanel.find('textarea.limited')) {
            $querySelectPanel.find('textarea.limited').inputlimiter({
                remText: '还可以输入 %n 个字符, ',
                limitText: '最多可以输入 %n 个字符数.'
            });
        }

        //datepicker plugin init
        if ($querySelectPanel.find('.date-picker')) {
            $querySelectPanel.find('.date-picker').datepicker({
                language: 'zh-CN',
                autoclose: true,//选中之后自动隐藏日期选择框
                todayHighlight: true,
                clearBtn: true,//清除按钮
                format: 'yyyy-mm-dd'//日期格式
            }).on('changeDate', function (ev) {
                $(this).closest('form').validate().element($(this));
            }).next().on(ace.click_event, function () {
                $(this).prev().focus();
            });
        }

        //daterange plugin init
        if ($querySelectPanel.find('.input-daterange')) {
            $querySelectPanel.find('.input-daterange').datepicker({
                language: 'zh-CN',
                autoclose: true,//选中之后自动隐藏日期选择框
                todayHighlight: true,
                clearBtn: true,//清除按钮
                format: 'yyyy-mm-dd'//日期格式
            });
        }

        //date-timepicker plugin init
        if ($querySelectPanel.find('.date-timepicker')) {
            if (!ace.vars['old_ie']) {
                $querySelectPanel.find('.date-timepicker').datetimepicker({
                    locale: 'zh_cn',
                    showTodayButton: true,
                    showClear: true,
                    format: 'YYYY-MM-DD HH:mm:ss'//use this option to display seconds MM/DD/YYYY h:mm:ss A
                }).next().on(ace.click_event, function () {
                    $(this).prev().focus();
                });
            }
        }

        //chosen-select plugin init
        if (!ace.vars['touch']) {
            if ($querySelectPanel.find('.chosen-select')) {
                $querySelectPanel.find('.chosen-select').chosen({
                    allow_single_deselect: true
                });
            }
            //resize the chosen on window resize
            $(window).off('resize.chosen').on('resize.chosen', function () {
                rseizeSelect_select();
            }).trigger('resize.chosen');
            //resize chosen on sidebar collapse/expand
            $(document).on('settings.ace.chosen', function (e, event_name, event_val) {
                if (event_name != 'sidebar_collapsed') return;
                rseizeSelect_select();
            });
        }
    };
};